package ichubmetadata

import (
	"encoding/json"
	"gitee.com/ichub/webcli/common/base/basedto"
	"gitee.com/ichub/webcli/common/base/metadata/indexmetadata"
	"strings"
)

/*
@Title    文件名称: metadata_tables.go
@Description  描述: 元数据--表信息

@Author  作者: leijianming@163.com  时间(2024-01-31 22:38:21)
@Update  作者: leijianming@163.com  时间(2024-01-31 22:38:21)
*/
type MetadataTable struct {
	basedto.BaseEntity

	TableSchema  string            `json:"table_schema" gorm:"column:table_schema"`
	TableName    string            `json:"table_name" gorm:"column:table_name"`
	TableComment string            `json:"table_comment" gorm:"column:table_comment"`
	PkInfo       *MetadataPkInfo   `json:"pk_info,omitempty"`
	Cols         []MetadataColumn  `json:"cols"`
	GoFields     []MetadataGoField `json:"go_fields"`

	TableExist    bool `json:"table_exist"`
	FieldsName    string
	IndexName     string
	IndexMetadata *indexmetadata.EsIndexMetadata
}

func (this *MetadataTable) Parse2EsIndex() {
	this.IndexName = this.TableName
	this.IndexMetadata = indexmetadata.NewIndexMetadata()
	this.IndexMetadata.SetIndexName(this.IndexName)
	for _, c := range this.Cols {
		var estype = c.FindColEsType()
		this.IndexMetadata.AddField(c.ColumnName, estype)
	}
}
func (this *MetadataTable) ToMapping() map[string]interface{} {
	this.Parse2EsIndex()
	return this.IndexMetadata.ToMapping()

}

func (this *MetadataTable) ToMappingStr() string {
	return this.IndexMetadata.ToMappingStr()

}
func NewMetadataTable() *MetadataTable {
	var meta = &MetadataTable{}
	meta.InitProxy(meta)
	meta.GoFields = []MetadataGoField{}
	meta.IndexMetadata = indexmetadata.NewIndexMetadata()
	return meta
}
func (this *MetadataTable) ToFieldsString() string {
	var sb = strings.Builder{}
	for _, v := range this.Cols {
		if sb.Len() == 0 {
			sb.WriteString(v.ColumnName)
		} else {
			sb.WriteString("," + v.ColumnName)
		}
	}
	return sb.String()

}

//build2GoFields

func (this *MetadataTable) BuildGoFields() {
	for _, v := range this.Cols {
		var gof = NewMetadatGoField()
		gof.DataType = v.DataType
		gof.ColumnName = v.ColumnName
		gof.GoType = v.FindColGoType() //(v.DataType)
		this.GoFields = append(this.GoFields, *gof)
	}
}

func (this *MetadataTable) ToString() string {
	s, _ := json.Marshal(this)
	return string(s)

}

func (this *MetadataTable) FindGoType(field string) string {
	for _, v := range this.GoFields {
		if v.ColumnName == field {
			return v.GoType
		}
	}
	return "string"
}
